# -*- coding: utf-8 -*-

import os
import sys
import urlparse
import urllib
import locale
import threading
import time
import subprocess
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
import urllib2
import json

__addon_id__ = 'plugin.resolver.undermedia'
__addon__ = xbmcaddon.Addon(id=__addon_id__)
__addonversion__ = __addon__.getAddonInfo('version')
__addonname__ = __addon__.getAddonInfo('name')
# __addonpath__ = __addon__.getAddonInfo('path').decode('utf-8')
__localize__ = __addon__.getLocalizedString

__addon_lib_id__ = xbmcaddon.Addon(id='service.undermedia.sync')
libraries = os.path.join(__addon_lib_id__.getAddonInfo('Path') , 'lib')
sys.path.append (libraries)

import undermedia

# Get the platform and architecture
system_platform = 'Unknown'
architecture = ''

# struct.calcsize("P") is 4 or 8 for 32 or 64 bit Python repectively
# sys.maxsize > 2**32 would be nice to use but is only available from Pyton 2.6
# if struct.calcsize("P") == 8:
if sys.maxsize > 2 ** 32:
    architecture = '64bit'
else:
    architecture = '32bit'

if xbmc.getCondVisibility("system.platform.linux"):
    # xbmc.log(os.path.join(plugintools.get_runtime_path(), 'resources', 'bin', 'getuuid_linux.sh'))
    # system_uuid = subprocess.Popen(os.path.join( plugintools.get_runtime_path(), 'resources', 'getuuid_linux.sh'), stdout=subprocess.PIPE, shell=True).communicate()[0]
    system_platform = 'Linux'
    if 'arm' in os.uname()[4]:
        architecture = 'arm'
elif xbmc.getCondVisibility("system.platform.xbox"):
    system_platform = 'Xbox'
    # No architecture directory for Xbox
    architecture = ''
elif xbmc.getCondVisibility("system.platform.windows"):
    system_platform = 'Windows'

elif xbmc.getCondVisibility("system.platform.osx"):
    # xbmc.log(os.path.join('resources', 'getuuid_macosx.sh'))
    # system_uuid = commands.getoutput('/bin/pwd')
    # system_uuid = subprocess.Popen(.split(), stdout=subprocess.PIPE).communicate()[0]
    
    system_platform = 'Darwin'
    if 'RELEASE_ARM' in os.uname()[3]:
        architecture = 'ios'
    else:
        # Crypto can be compiled as universal library with multiple
        # architectures for osx
        architecture = 'osx'

elif xbmc.getCondVisibility("system.platform.ios"):
    # Need to check system.platform.osx for eden
    # Changed to system.platform.ios for frodo
    system_platform = 'Darwin'
    architecture = 'ios'

elif xbmc.getCondVisibility("system.platform.android"):
    system_platform = 'Android'
    architecture = ''

from xbmcswift2 import Plugin, ListItem

plugin = Plugin(__addonname__, __addon_id__, __file__, 'video')
plugin.log.info("System Platform: " + system_platform)
plugin.log.info("System Architecture: " + architecture)
plugin.log.info("Type: " + plugin.info_type)
plugin.log.info("Name: " + __name__)

@plugin.route('/')
def index():
    plugin.log.info("To make a dialog for denied call")
        
'''
 
'''
@plugin.route('/resolve/<link>')
def resolve(link):
    plugin.log.info('Decrypting link: %s' % link)
    
    response = undermedia.getUrlData(undermedia.APIURL + '/resolve/?' + urllib.urlencode({'user' : undermedia.UMTVUSERNAME, 'secret' : undermedia.HPASSWORD, 'link' : link }))
    if response['video_url'].startswith("rtmp://"):
        response['video_url'] = response['video_url'] + " swfUrl=" + response['param_swfurl'] + " live=false pageUrl=" + response['video_url']
    play_movie = True
    if undermedia.ASKFORTRAILERVIEW and response['trailer_url'] != '':
        trailer_ok = xbmcgui.Dialog().yesno("Do you want to see the trailer first?", "You can modify this behavior in Add-on settings", "")
        if trailer_ok == 1:
            play_movie = False
            response['video_url'] = response['trailer_url']
            plugin.log.info('video_url replaced with trailer: %s' % response['video_url'])
    
    
    choice_subtitle = False
    if play_movie == True and response.get('subtitles'):
        lang_dict = {'none': 'None', 'en': 'English', 'es': 'Spanish'}
        lang_dict_inversed = { 'None' : False, 'English' : 'en', 'Spanish' : 'es'}
        lang_codes = []
        lang_codes_inv = []
        lang_codes.append(lang_dict['none'])
        lang_codes_inv.append(lang_dict_inversed[lang_dict['none']])
        
        for idx in response['subtitles']:
            lang_codes.append(lang_dict[idx])
            lang_codes_inv.append(lang_dict_inversed[lang_dict[idx]])
        choice_subtitle = xbmcgui.Dialog().select('Select Subtitle Language' , lang_codes)
     
    plugin.log.info('Playing url: %s' % response['video_url'])
    listitem = ListItem(label=response['title'], icon=response['thumbnail'], thumbnail=response['thumbnail'], path=response['video_url'])
    #listitem.set_property("IsLive", "false")
    plugin.set_resolved_url(listitem)
    
    if choice_subtitle != False:
        plugin.log.info('Selected Language for Subtitles : %s' % lang_codes_inv[choice_subtitle])
        plugin.log.info('Selected Url for Subtitles : %s' % response['subtitles'][lang_codes_inv[choice_subtitle]])
        subtitle = undermedia.fetchPage({"link": response['subtitles'][lang_codes_inv[choice_subtitle]]})
        undermedia.ensureDir(os.path.join(xbmc.translatePath(__addon__.getAddonInfo("profile")).decode("utf-8"), 'subtitles_cached'))
        subtitle_path = os.path.join(xbmc.translatePath(__addon__.getAddonInfo("profile")).decode("utf-8"), 'subtitles_cached', subtitle["filename"])
        subtitle_file = open(subtitle_path, 'w')
        subtitle_file.write(subtitle["content"])
        subtitle_file.close()
        player = xbmc.Player()
        i = 0
        while not player.isPlaying():
            i += 1
            plugin.log.info("Waiting for playback to start ")
            time.sleep(1)
            if i > 10:
                break
        plugin.log.info("Setting subtitle file %s" % subtitle_path)
        xbmc.Player().setSubtitles(subtitle_path)

if __name__ == '__main__':
    plugin.log.info('__main__')
    plugin.run()
